package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.DeptMapper;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
@AllArgsConstructor
public class EmpServiceImpl extends ServiceImpl<EmpMapper, Emp> implements EmpService {


    private EmpMapper empMapper;
    private DeptService deptService;
    private DeptMapper deptMapper;
    private EmpExprService exprService;


//    @Override
//    public void queryPage(EmpQueryParam param) {
//        // 查询姓名中包含“李”且薪资大于等于5000的员工的 id, name, phone, salary字段
//        QueryWrapper<Emp> queryWrapper = new QueryWrapper<>();
//        queryWrapper.like("name","李")
//                .ge("salary",5000)
//                .select("id","name","phone","salary");
//        List<Emp> empList = empMapper.selectList(queryWrapper);
//        empList.forEach(System.out::println);
//    }

    @Override
    public PageResult<Emp> queryPage(EmpQueryParam param) {
//        HttpServletRequest

//        lambdaQuery()

        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        LambdaQueryWrapper<Emp> queryWrapper = new LambdaQueryWrapper<>();
//        queryWrapper.like(Emp::getName, param.getName())
//                        .eq(Emp::getGender, param.getGender())
//                                .between(Emp::getEntryDate, param.getBegin(), param.getEnd());
//        page.setOrders(OrderItem.descs("update_time"));




        queryWrapper.like(param.getName() != null && !param.getName().isEmpty(), Emp::getName, param.getName())
                .eq(param.getGender() != null, Emp::getGender, param.getGender())
                .between(param.getBegin() != null && param.getEnd() != null, Emp::getEntryDate, param.getBegin(), param.getEnd());


        page = page(page, queryWrapper);
        List<Emp> emps = page.getRecords();
        List<Integer> empIds = emps.stream().map(Emp::getDeptId).collect(Collectors.toList());

        List<Dept> depts = deptService.listByIds(empIds);
        emps.forEach(emp -> {
            depts.stream().filter(dept -> dept.getId().equals(emp.getDeptId()))
                    .findFirst().ifPresent(dept -> emp.setDeptName(dept.getName()));
        });

        Page<Emp> page1 = lambdaQuery().like(StringUtils.hasLength(param.getName()), Emp::getName, param.getName())
                .eq(null != param.getGender(), Emp::getName, param.getGender())
                .between(param.getBegin() != null && null != param.getEnd(), Emp::getEntryDate, param.getBegin(), param.getEnd())
                .page(page);

        //会获得dept信息，再将dept的name插入到emp中。用流过滤
        List<Integer> deptids = emps.stream().map(Emp::getDeptId).collect(Collectors.toList());
        List<Dept> deptList = deptService.listByIds(deptids);
        List<Dept> depts1 = deptMapper.selectBatchIds(deptids);

        //为每一个员工设置部门名称
        page1.getRecords().forEach(
                emp -> {
                    depts1.stream().filter(dept -> dept.getId().equals(emp.getDeptId()) )
                            .findFirst().ifPresent(dept -> emp.setDeptName(dept.getName()));
                }
        );

//        deptMapper.selectBatchIds(deptids);
        return new PageResult(page.getTotal(), emps);
    }

    @Override
    public void saveEmp(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        emp.setCreateTime(emp.getUpdateTime());
        List<EmpExpr> exprList = emp.getExprList();
        //为工作经历设置
        exprList.forEach(expr -> expr.setEmpId(emp.getId()));
//        exprList.stream().collect(Collectors.groupingBy()
        exprService.saveBatch(exprList);
        empMapper.insert(emp);
    }

    @Override
    public Emp getEmpById(Integer id) {
        Emp emp = empMapper.selectById(id);

//        exprService.getById(id).
        //耦合不好
//        LambdaQueryWrapper<EmpExpr> wrapper = new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, id);
//        emp.setExprList(exprService.list(wrapper));

        emp.setExprList(exprService.getByEmpId(id));
        return emp;
    }

    @Override
    public void updateEmp(Emp emp) {
        List<EmpExpr> exprList = emp.getExprList();
        emp.setUpdateTime(LocalDateTime.now());
        //直接删除原有的
//        EmpExpr::getEmpId.
        LambdaQueryWrapper<EmpExpr> wrapper = new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId());
        exprService.remove(wrapper);
        //判断工作经历是否为空
        if (!CollectionUtils.isEmpty(exprList)) {
            exprList.forEach(expr -> expr.setEmpId(emp.getId()));

            //直接删除原有的
//        EmpExpr::getEmpId.
//            LambdaQueryWrapper<EmpExpr> wrapper = new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId());
//            exprService.remove(wrapper);
            exprService.saveBatch(exprList);
        }

        empMapper.updateById(emp);
    }

    @Override
    public void deleteEmp(List<Integer> ids) {
        if (!CollectionUtils.isEmpty(ids)){

            //删除员工
            removeBatchByIds(ids);
//            deleteByIds(ids);


            exprService.deleteByEmpIds(ids);

        }

    }
}
